/** 
 * 视频链接控制器模块
 */
module controller.PlaylinkController;

import vibe.http.server : HTTPServerRequest, HTTPServerResponse;
import vibe.data.json : Json;

import repository.PlaylinkRepo;

import utils.RespData;
import utils.Playlink : Playlink;
import utils.DataCache;
import utils.CacheKey : CacheKey;
import utils.SecurityVerification : signValidator;

// import std.stdio;

PlaylinkRepo _plRepo; // playlink仓储

static this ()
{
    _plRepo = new PlaylinkRepo();
}

static ~this ()
{
    destroy(_plRepo);
}

/** 
* 解析视频播放地址
*/
void parsePlaylink (HTTPServerRequest req, HTTPServerResponse resp)
{
    import std.algorithm : canFind, endsWith;
    import std.concurrency : scheduler, FiberScheduler;
    import std.format : format;
    import vibe.data.json : Json;

    string[] vcates = ["teleplay", "movie", "animation"];

    Json json = req.json;
    string vcate = json["vcate"].to!string();
    // string vid = json["vid"].to!string();
    string url = json["url"].to!string();
    string sign = json["sign"].to!string();

    // 判空
    if (vcate == "" || url == "")
    {
        resp.writeJsonBody(RespData.newData(400, "错误的请求"), 400);
        return;
    }
    if (!canFind(vcates, vcate))
    {
        resp.writeJsonBody(RespData.newData(400, "错误的请求"), 400);
        return;
    }

    string reqParamsStr = format("%s%s", vcate, url);
    if (!signValidator(reqParamsStr, sign))
    {
        resp.writeJsonBody(RespData.newData(403, "签名不正确！"), 403);
        return;
    }

    string vtable = vcate ~ "_vlinks";

    // 缓存中有数据直接取出返回
    auto data = cacheData.get(url);
    if (!data.isNull)
    {
        resp.writeJsonBody(RespData.newData(200, "ok", Json(data.get)));
        return;
    }

    // 缓存中没有,则从数据库中查询是否有真实地址
    string realUrl = _plRepo.getRealUrl(vtable, url);
    if (realUrl == "") // 数据库中没有
    {
        // 进行网络请求获取
        string realUrlFromNet = Playlink.getRealPlaylink(url);
        if (endsWith(realUrlFromNet, `.m3u8`))
        {
            // 接口1 https://video.isyour.love/player/getplayer?url=
            // 接口2 https://www.playm3u8.cn/jiexi.php?url=
            // 接口3 https://jx.2s0.cn/player/?url=
            // 接口4 https://jx.jsonplayer.com/player/?url=
            // 接口5 https://jx.aidouer.net/?url=
            // 接口6 https://jx.xmflv.com/?url=
            // 接口7 https://www.yemu.xyz/?url=
            // 接口8 https://jx.wujinkk.com/dplayer/?url=
            realUrl = "https://jx.wujinkk.com/dplayer/?url=" ~ realUrlFromNet;
        }
        else
        {
            realUrl = realUrlFromNet;
        }

        if (realUrl !is null && realUrl != "")
        {
            // 更新数据库，保存真实地址
            scheduler = new FiberScheduler();
            scheduler.start({ _plRepo.updateLinkInfo(vtable, url, realUrl); });
        }
    }

    // 设置缓存
    cacheData.put(url, realUrl);
    resp.writeJsonBody(RespData.newData(200, "ok", Json(realUrl)));
}
